import {
  dateFormat
} from '@/utils/time'

export default {
  data() {
    return {
      timeArray: [],
      recordInfo: {
        queryForm: {
          page: 1,
          pageSize: 10
        },
        requestUrl: '',
        loading: true,
        list: [],
        total: 0
      },
      exportRequestUrl: '', // 导出路径
      defaultTime: ['00:00:00', '23:59:59'],
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            const end = new Date()
            end.setHours(23, 59, 59, 999)

            const start = new Date()
            start.setHours(0, 0, 0, 0)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const end = new Date()
            end.setTime(end.getTime() - 3600 * 1000 * 24)
            end.setHours(23, 59, 59, 999)

            const start = new Date()
            start.setHours(0, 0, 0, 0)
            start.setTime(start.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '近七天',
          onClick(picker) {
            const end = new Date()
            end.setHours(23, 59, 59, 999)

            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            start.setHours(0, 0, 0, 0)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '近三十天',
          onClick(picker) {
            const end = new Date()
            end.setHours(23, 59, 59, 999)

            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            start.setHours(0, 0, 0, 0)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '本月',
          onClick(picker) {
            const end = new Date()
            end.setHours(23, 59, 59, 999)

            const start = new Date()
            start.setDate(1)
            start.setHours(0, 0, 0, 0)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '上月',
          onClick(picker) {
            // 上个月的第一天
            const start = new Date()
            start.setMonth(start.getMonth() - 1)
            start.setDate(1)
            start.setHours(0, 0, 0, 0)

            const end = new Date()
            // 设置日期为上个月的最后一天
            end.setDate(0) // 将日期设置为0，会自动回滚到上个月的最后一天
            end.setHours(23, 59, 59, 999)

            picker.$emit('pick', [start, end])
          }
        }, {
          text: '今年',
          onClick(picker) {
            const end = new Date()
            end.setHours(23, 59, 59, 999)

            const start = new Date()
            // 设置月份为1（即1月），日期为1
            start.setMonth(0) // JavaScript中的月份是从0开始的，0代表1月
            start.setDate(1)
            start.setHours(0, 0, 0, 0)

            picker.$emit('pick', [start, end])
          }
        }, {
          text: '去年',
          onClick(picker) {
            let end = new Date()
            // 获取去年的年份
            const lastYear = end.getFullYear() - 1
            // 设置年份为去年，月份为12月（注意JavaScript中月份是从0开始的，所以12月是11），日期为31日
            end = new Date(lastYear, 11, 31)
            end.setHours(23, 59, 59, 999)

            const start = new Date()
            // 获取去年的年份
            const startLastYear = start.getFullYear() - 1
            // 设置年份为去年，月份和日期保持不变（默认为当前月份和日期）
            start.setFullYear(startLastYear)
            start.setMonth(0) // JavaScript中的月份是从0开始的，0代表1月
            start.setDate(1)
            start.setHours(0, 0, 0, 0)

            picker.$emit('pick', [start, end])
          }
        }]
      },
      datePickerValueFormat: 'timestamp',
      getRecordApi: '',
      autoGetList: true,
      getListCallback: undefined,
      callback: undefined,
      beforeRequest: undefined,
      changeDateNameInfo: undefined // 输入日期的时候需要转换的日期 例 {key:[]}
    }
  },
  created() {
    // this.timeArray = this.getCurrentTimeArray()
    // this.recordInfo.queryForm.crtDtStart = this.timeArray[0]
    // this.recordInfo.queryForm.crtDtEnd = this.timeArray[1]
    if (this.autoGetList) {
      this.getRecordList()
    }
  },
  methods: {
    _queryFilter() {
      const params = {}
      if (undefined === this.recordInfo.queryForm.page) {
        this.recordInfo.queryForm.page = 1
      }
      for (const key in this.recordInfo.queryForm) {
        if (this.recordInfo.queryForm[key] instanceof Date) {
          if (key.indexOf('imeStart') >= 0) {
            params[key] = dateFormat(new Date(new Date(new Date(this.recordInfo.queryForm[key]).toLocaleDateString())
              .getTime()), 'yyyy-MM-dd hh:mm:ss')
          } else if (key.indexOf('imeEnd') >= 0) {
            params[key] = dateFormat(new Date(new Date(new Date(this.recordInfo.queryForm[key]).toLocaleDateString())
              .getTime() + 24 * 60 * 60 * 1000 - 1), 'yyyy-MM-dd hh:mm:ss')
          } else {
            params[key] = dateFormat(this.recordInfo.queryForm[key], 'yyyy-MM-dd hh:mm:ss')
          }
        } else if (key !== 'notSubmit' && undefined !== this.recordInfo.queryForm[key] && this.recordInfo
          .queryForm[key] !== null && this.recordInfo.queryForm[key] !== '') {
          params[key] = this.recordInfo.queryForm[key]
        }
      }
      return this.$commonUtils.filterFormParam(params)
    },
    queryFilter() {
      return {}
    },
    // 获取当天的年月日
    getCurrentTimeArray(datePickerValueFormat) {
      const valueFormat = datePickerValueFormat || this.datePickerValueFormat
      // 获取今天的日期
      const today = new Date()
      // 获取今天00:00的时间戳
      let startTimestamp = today.setHours(0, 0, 0, 0)
      // 获取今天23:59的时间戳
      let endTimestamp = today.setHours(23, 59, 59, 0)
      switch (valueFormat) {
        case 'yyyy-MM-dd HH:mm:ss':
          startTimestamp = this.$commonUtils.formatDate(new Date(startTimestamp), 'yyyy-MM-dd 00:00:00')
          endTimestamp = this.$commonUtils.formatDate(new Date(endTimestamp), 'yyyy-MM-dd 23:59:59')
          break
      }
      return [startTimestamp, endTimestamp]
    },
    changeDate(array, changeDateName) {
      if (!changeDateName) {
        return
      }
      let startTime = ''
      let endTime = ''
      const changeDateNameInfo = this.changeDateNameInfo
      if (array?.length > 0 && changeDateNameInfo && this.datePickerValueFormat === 'timestamp') {
        startTime = new Date(array[0]).getTime()

        const today = new Date(array[1])
        endTime = today.setHours(23, 59, 59, 0)
      }
      const startTimeName = changeDateNameInfo[changeDateName][0]
      const endTimeName = changeDateNameInfo[changeDateName][1]

      this.recordInfo.queryForm[startTimeName] = startTime
      this.recordInfo.queryForm[endTimeName] = endTime
    },
    getRecordList: async function() {
      try {
        if (!this.recordInfo.requestUrl) {
          return
        }
        if (undefined !== this.beforeRequest) {
          const execute = this.beforeRequest()
          if (undefined !== execute && execute === false) {
            return
          }
        }
        let params = this._queryFilter()
        params = {
          ...params,
          ...this.queryFilter()
        }
        if (undefined === params.returnCount) {
          params.returnCount = params.page === 1
        }
        this.recordInfo.loading = true
        const getRecordResult = await this.recordInfo.requestUrl(params, {
          showLoading: false
        })
        if (getRecordResult?.list?.length > 0) {
          for (let i = 0; i < getRecordResult.list.length; i++) {
            if (getRecordResult.list[i].distributorPrintTime) {
              if (getRecordResult.list[i].distributorPrintTime === '') {
                getRecordResult.list[i].distributorPrintTimeChecked = false
              } else {
                getRecordResult.list[i].distributorPrintTimeChecked = true
              }
            }
          }
        }
        if (params.page === 1) {
          this.recordInfo.total = Number(getRecordResult.count)
        }
        if (getRecordResult.list) {
          this.recordInfo.list = getRecordResult.list
        } else {
          this.recordInfo.list = []
        }
        this.recordInfoForm = getRecordResult
        // 加载完回调，方便在页面处理其他逻辑
        if (undefined !== this.callback) {
          this.callback(getRecordResult)
        }
        if (undefined !== this.getListCallback) {
          this.getListCallback(getRecordResult)
        }
        // this.recordInfo.list = refresh ? getRecordResult.list : [...this.recordInfo.list, ...getRecordResult.list]
      } catch (err) {
        console.error(err)
      } finally {
        setTimeout(() => {
          this.recordInfo.loading = false
        }, 300)
      }
    },
    exportData() {
      const execute = this.beforeRequest && this.beforeRequest()
      if (undefined !== execute && execute === false) {
        return
      }
      this.$commonUtils.showLoading()
      const param = this.$commonUtils.filterFormParam(this.recordInfo.queryForm)
      this.exportRequestUrl(param).then(res => {
        this.$commonUtils.hideLoading()
        this.$confirm('导出成功！', '提示', {
          confirmButtonText: '下载',
          cancelButtonText: '关闭',
          closeOnClickModal: false,
          type: 'success'
        }).then(() => {
          window.open(this.$api.getDownloadServiceUrl(res.fileDownloadCode))
        }).catch(() => {})
      }, _ => {
        this.$commonUtils.hideLoading()
      })
    }
  }
}
